﻿
Imports System.Collections
Imports System.Collections.Generic
Imports System.Configuration.Provider
Imports System.Globalization
Imports System.Linq
Imports System.ServiceModel.Syndication
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Xml


Namespace Providers


    ''' <summary>
    ''' Manages storage of picture information in the file system
    ''' </summary>
    Public Class FlickrPictureProvider
        Inherits PictureProvider
        Private Const STR_Description As String = "description"
        Private Const STR_Feeds As String = "feeds"




        Private _FeedList As String()
        Public Property FeedList() As String()
            Get
                Return _FeedList
            End Get
            Set(ByVal value As String())
                _FeedList = value
            End Set
        End Property





        Public Overrides Sub Initialize(ByVal name As String, ByVal config As System.Collections.Specialized.NameValueCollection)


            If config Is Nothing OrElse config.Count = 0 Then Throw New ArgumentNullException("You must supply a valid configuration dictionary.")

            If String.IsNullOrEmpty(config(STR_Description)) Then
                config.Remove(STR_Description)
                config.Add(STR_Description, "Put a localized description here.")
            End If

            'Let ProviderBase perform the basic initialization
            MyBase.Initialize(name, config)

            Dim feeds As String = config(STR_Feeds)

            If String.IsNullOrEmpty(feeds) Then Throw New ProviderException("No feeds defined")

            FeedList = feeds.Split("|".ToCharArray)

            config.Remove(STR_Feeds)

            'Check to see if unexpected attributes were set in configuration

            If config.Count > 0 Then


                Dim extraAttribute As String = config.GetKey(0)

                If Not String.IsNullOrEmpty(extraAttribute) Then
                    Throw New ProviderException(String.Format("The following unrecognized attribute was found in {0}'s configuration: '{1}'", name, extraAttribute))
                Else
                    Throw New ProviderException("An unrecognized attribute was found in the provider's configuration.")
                End If


            End If



        End Sub




        Public Overrides Function GetPictureById(ByVal pictureId As String) As Picture
            Dim dict As Dictionary(Of Integer, Picture) = GetPictures.ToDictionary(Function(k) (Integer.Parse(k.Id)))

            Dim parsedId As Integer

            If Not Integer.TryParse(pictureId.Substring(0, pictureId.LastIndexOf(".", StringComparison.Ordinal)), parsedId) Then Return Nothing

            If Not dict.ContainsKey(parsedId) Then Return Nothing

            Return dict(parsedId)
        End Function


        Public Overrides Function GetPictures() As System.Collections.Generic.List(Of Picture)
            Dim list As New List(Of Picture)

            For Each feedUri As String In FeedList
                Dim feedReader = XmlReader.Create(feedUri)

                Dim feed = SyndicationFeed.Load(feedReader)

                For Each item In feed.Items

                    Dim p As New Picture

                    With p
                        .Id = item.Id.Substring(item.Id.LastIndexOf("/", StringComparison.Ordinal) + 1)

                        .Title = item.Title.Text
                        .DateCreated = item.PublishDate
                        .DateModified = item.LastUpdatedTime
                        .Tags = item.Categories.Select(Function(c) (c.Name)).ToArray()

                        Dim enclosure As SyndicationLink = item.Links.Single(Function(link) (String.Compare(link.RelationshipType, "enclosure", StringComparison.Ordinal) = 0))

                        .MimeType = enclosure.MediaType
                        .ItemUrl = enclosure.Uri
                        .FileName = enclosure.Uri.LocalPath.Substring(enclosure.Uri.LocalPath.LastIndexOf("/", StringComparison.Ordinal) + 1)
                        .FileExtension = .FileName.Substring(.FileName.LastIndexOf(".", StringComparison.Ordinal))

                    End With

                    list.Add(p)

                Next

            Next

            Return list.OrderByDescending(Function(p) (p.DateModified)).ToList()
        End Function






        Public Overrides Function GetPicturesByTag(ByVal tagName As String) As System.Collections.Generic.List(Of Picture)
            Return GetPictures.Where(Function(p) (p.Tags.Contains(tagName))).ToList
        End Function
    End Class

End Namespace
